package com.llkj.contractmanagement.utils;


import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.Size;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Build.VERSION_CODES;
import android.os.Environment;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.telephony.TelephonyManager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.widget.TextView;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

public class Utils {
    public static String path = null;
    public static final String IMAGE_UNSPECIFIED = "image/*";
    public static final int PHOTORESOULT = 0;// 结果
    public static final int REQUEST_CODE_CAMERA = 1;
    public static final int REQUEST_CODE_GALLERY = 2;

    /**
     * 获取库Phon表字段
     **/
    private static final String[] PHONES_PROJECTION = new String[]{
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Photo.PHOTO_ID, ContactsContract.CommonDataKinds.Phone.CONTACT_ID};
    /**
     * 联系人显示名称
     **/
    private static final int PHONES_DISPLAY_NAME_INDEX = 0;
    /**
     * 电话号码
     **/
    private static final int PHONES_NUMBER_INDEX = 1;
    /**
     * 头像ID
     **/
    private static final int PHONES_PHOTO_ID_INDEX = 2;
    /**
     * 联系人的ID
     **/
    private static final int PHONES_CONTACT_ID_INDEX = 3;

    /**
     * 判断当前是否有网络
     *
     * @param context
     * @return
     */
    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager
                    .getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    /**
     * 获取应用程序版本名称信息
     *
     * @param context
     * @return 当前应用的版本名称
     */
    public static String getVersionName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            return packageInfo.versionName;

        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取应用程序版本名称信息
     *
     * @param context
     * @return 当前应用的版本名称
     */
    public static int getVersionCode(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * long时间转换成yyyy-MM-dd HH:mm:ss
     *
     * @return
     */
    public static String LongTimeChange(long time) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = format.format(new Date(time));
        return date;
    }

    /**
     * long时间转换成yyyy-MM-dd
     *
     * @return
     */
    public static String LongTimeChangeTwo(long time) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(new Date(time));
    }

    /**
     * long时间转换成yyyy-MM-dd
     *
     * @return
     */
    public static String LongTimeChangeThree(long time) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        return format.format(new Date(time));
    }


    /**
     * Date转换成yyyy年-MM月-dd日格式
     *
     * @return
     */
    public static String DateToString(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy年-MM月-dd日");
        String str = format.format(date);
        return str;
    }

    /**
     * String时间转换成yyyy-MM-dd格式
     *
     * @return
     */
    public static String StringToString(String time) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return format.format(format.parse(time));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Date时间转换成hh-mm格式  12进制
     *
     * @return
     */
    public static String DateToStringOne(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    /**
     * string yyyy-MM-dd 时间转换成date
     *
     * @return
     */
    public static Date StringToDate(String time) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try {
            return format.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * string yyyy-MM-dd 时间转换成date
     *
     * @return
     */
    public static Date StringToDateOne(String time) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return format.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static SpannableString getSpannableString(Context context,
                                                     ArrayList<String> str, ArrayList<Float> text_size_list) {
        // 累加数组所有的字符串为一个字符串
        StringBuffer long_str = new StringBuffer();
        for (int i = 0; i < str.size(); i++) {
            long_str.append(str.get(i));
        }
        SpannableString builder = new SpannableString(long_str.toString());
        // 设置不同字符串的字号
        ArrayList<AbsoluteSizeSpan> absoluteSizeSpans = new ArrayList<AbsoluteSizeSpan>();
        for (int i = 0; i < text_size_list.size(); i++) {
            absoluteSizeSpans.add(new AbsoluteSizeSpan(ScreenUtil.sp2px(
                    context, text_size_list.get(i))));
        }
        for (int i = 0; i < str.size(); i++) {
            int star = long_str.toString().indexOf(str.get(i));
            int end = star + str.get(i).length();
            builder.setSpan(absoluteSizeSpans.get(i), star, end,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return builder;
    }

    public static void setTextColor(String str, TextView tv,
                                    int startIndex, int endIndex, Integer color) {
        SpannableString msp = new SpannableString(str);
        msp.setSpan(new ForegroundColorSpan(color), startIndex, endIndex,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tv.setText(msp);
    }

    /**
     * 格式化数字
     *
     * @param
     * @return
     */
    public static String DoubleToString(Double str) {
        NumberFormat numberFormat = NumberFormat.getInstance();
        numberFormat.setMinimumFractionDigits(2);
        numberFormat.setMaximumFractionDigits(2);
        numberFormat.setGroupingUsed(false);
        return numberFormat.format(str);
    }

    /**
     * 获取app的存储目录
     * <p/>
     * 一般情况下是这样的/storage/emulated/0/Android/data/包名/
     *
     * @param context
     * @return
     */
    public static String getAppDir(Context context) {
        return (Environment.MEDIA_MOUNTED.equals(Environment
                .getExternalStorageState()) ? (Environment
                .getExternalStorageDirectory().getPath() + "/Android/data/")
                : (context.getCacheDir().getPath()))
                + context.getPackageName();
    }

    /**
     * 开启一个系统页面来裁剪传进来的照片
     *
     * @param uri 需要裁剪的照片的URI值
     */
    public static void startPhotoZoom(Activity activity, Uri uri) {
        // 裁剪图片意图
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("return-data", true);
        activity.startActivityForResult(intent, PHOTORESOULT);
    }

    /**
     * 通过相册获取
     */
    public static void getAvatarFromGallery(Context context) {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_PICK);
        ((Activity) context).startActivityForResult(intent,
                REQUEST_CODE_GALLERY);
    }

    /**
     * 通过拍照获取头像
     */
    public static void getAvatarFromCamera(Context context) {
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        ((Activity) context).startActivityForResult(intent,
                Utils.REQUEST_CODE_CAMERA);
    }

    /**
     * 通过拍照获取
     */
    public static void photo(Context context) {

        Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        String status = Environment.getExternalStorageState();
        if (status.equals(Environment.MEDIA_MOUNTED)) {
            String filePath = getAppDir(context) + "/image/";
            File files = new File(filePath);
            if (!files.exists()) {
                files.mkdirs();
            }

            File file = new File(filePath, String.valueOf(System
                    .currentTimeMillis()) + ".jpg");
            // try {
            // file.createNewFile();
            // } catch (IOException e) {
            //
            // e.printStackTrace();
            // }
            path = file.getPath();
            Uri imageUri = Uri.fromFile(file);
            openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        } else {
            ToastUtil.makeShortText(context, "请插入内存卡");
        }
        ((Activity) context).startActivityForResult(openCameraIntent,
                REQUEST_CODE_CAMERA);
        // return openCameraIntent;
    }

    /**
     * 获取设备ID
     *
     * @param context
     * @return
     */
    public static String getIMEI(Context context) {
        TelephonyManager manager = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        if (!TextUtils.isEmpty(manager.getDeviceId())) {
            return manager.getDeviceId();
        } else {
            final String tmDevice, tmSerial, tmPhone, androidId;

            tmDevice = "" + manager.getDeviceId();

            tmSerial = "" + manager.getSimSerialNumber();

            androidId = ""
                    + android.provider.Settings.Secure.getString(
                    context.getContentResolver(),
                    android.provider.Settings.Secure.ANDROID_ID);

            UUID deviceUuid = new UUID(androidId.hashCode(),
                    ((long) tmDevice.hashCode() << 32) | tmSerial.hashCode());

            String uniqueId = deviceUuid.toString();

            LogUtil.e("android deviceId is null, uuid=" + uniqueId);
            return uniqueId;
        }
    }

    /**
     * 获取应用AppKey
     *
     * @return
     */
    public static String getAppKey(Context context) {
        ApplicationInfo applicationInfo = null;
        String appKey = null;
        try {
            applicationInfo = context.getPackageManager().getApplicationInfo(
                    context.getPackageName(), PackageManager.GET_META_DATA);
            appKey = applicationInfo.metaData.getString("app_key");
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        LogUtil.i("app_key=" + appKey);
        return appKey;
    }

    public static String getAppSecret(Context context) {
        ApplicationInfo applicationInfo = null;
        String appSecret = null;
        try {
            applicationInfo = context.getPackageManager().getApplicationInfo(
                    context.getPackageName(), PackageManager.GET_META_DATA);
            appSecret = applicationInfo.metaData.getString("app_secret");
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        LogUtil.i("app_secret=" + appSecret);
        return appSecret;
    }

    public static boolean hasSDCard() {
        String state = Environment.getExternalStorageState();
        return state.equals(Environment.MEDIA_MOUNTED);
    }

    /**
     * bitmap转成byte数组
     *
     * @param avatar
     * @return
     */
    public static byte[] Bitmap2Bytes(Bitmap avatar) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        avatar.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        return baos.toByteArray();

    }

    public interface IContactCallback {
        void callback(String string);

        void callback(ArrayList<HashMap<String, String>> data);
    }

    public static boolean hasFroyo() {
        return Build.VERSION.SDK_INT >= VERSION_CODES.FROYO;

    }

    public static boolean hasGingerbread() {
        return Build.VERSION.SDK_INT >= VERSION_CODES.GINGERBREAD;
    }

    public static boolean hasHoneycomb() {
        return Build.VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB;
    }

    public static boolean hasHoneycombMR1() {
        return Build.VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB_MR1;
    }

    public static boolean hasJellyBean() {
        return Build.VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN;
    }

    public static boolean hasKitKat() {
        return Build.VERSION.SDK_INT >= 19;
    }

    public static List<Size> getResolutionList(Camera camera) {
        Parameters parameters = camera.getParameters();
        List<Size> previewSizes = parameters.getSupportedPreviewSizes();
        return previewSizes;
    }

    public static class ResolutionComparator implements Comparator<Size> {

        @Override
        public int compare(Size lhs, Size rhs) {
            if (lhs.height != rhs.height)
                return lhs.height - rhs.height;
            else
                return lhs.width - rhs.width;
        }
    }

    public static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    public static byte[] hex2Bytes1(String src) {
        byte[] res = new byte[src.length() / 2];
        char[] chs = src.toCharArray();
        int[] b = new int[2];

        for (int i = 0, c = 0; i < chs.length; i += 2, c++) {
            for (int j = 0; j < 2; j++) {
                if (chs[i + j] >= '0' && chs[i + j] <= '9') {
                    b[j] = (chs[i + j] - '0');
                } else if (chs[i + j] >= 'A' && chs[i + j] <= 'F') {
                    b[j] = (chs[i + j] - 'A' + 10);
                } else if (chs[i + j] >= 'a' && chs[i + j] <= 'f') {
                    b[j] = (chs[i + j] - 'a' + 10);
                }
            }

            b[0] = (b[0] & 0x0f) << 4;
            b[1] = (b[1] & 0x0f);
            res[c] = (byte) (b[0] | b[1]);
        }

        return res;
    }

    /**
     * 获取手机上的联系人电话.
     *
     * @return
     */
    public static void getContacts(Context context,
                                   final IContactCallback callback) {
        final Context ctx = context;
        new Thread(new Runnable() {
            @Override
            public void run() {
                ArrayList<HashMap<String, String>> contactsData = new ArrayList<HashMap<String, String>>();
                StringBuffer sb = new StringBuffer();
                Cursor cursor = ctx.getContentResolver().query(
                        ContactsContract.Contacts.CONTENT_URI, null, null,
                        null, null);
                if (cursor != null) {
                    while (cursor.moveToNext()) {
                        HashMap<String, String> contactMap = new HashMap<String, String>();
                        String contactId = cursor.getString(cursor
                                .getColumnIndex(ContactsContract.Contacts._ID));
                        String displayName = cursor.getString(cursor
                                .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                        int numberCount = cursor.getInt(cursor
                                .getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
                        contactMap.put("name", displayName);
                        LogUtil.e("联系人: " + displayName);
                        if (numberCount > 0) {
                            Cursor c = ctx
                                    .getContentResolver()
                                    .query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                                            null,
                                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID
                                                    + "=" + contactId, null,
                                            null);
                            if (c != null) {
                                while (c.moveToNext()) {
                                    String number = c.getString(c
                                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                                    if (number.contains(" ")) {
                                        number = number.replace(" ", "");
                                    }
                                    if (number.contains("-")) {
                                        number = number.replace("-", "");
                                    }
                                    // 截取后11位.针对前面有+86前缀的.
                                    if (number.length() > 11) {
                                        number = number.subSequence(
                                                number.length() - 11,
                                                number.length()).toString();
                                    }
                                    contactMap.put("phone", number);
                                    LogUtil.e("联系电话: " + number);
                                    sb.append(number);
                                    sb.append(",");
                                }
                                c.close();
                                c = null;
                            }
                        }
                    }
                    cursor.close();
                    cursor = null;
                }
                if (sb.toString().endsWith(",")) {
                    sb.delete(sb.length() - 1, sb.length());
                }
                callback.callback(sb.toString());
            }

        }).start();
    }

    /**
     * 获取手机上的联系人电话.
     *
     * @return
     */
    public static void getContacts2(Context context,
                                    final IContactCallback callback) {
        final Context ctx = context;
        new Thread(new Runnable() {
            @Override
            public void run() {
                ArrayList<HashMap<String, String>> contactsData = new ArrayList<HashMap<String, String>>();
                ContentResolver resolver = ctx.getContentResolver();

                // 获取手机联系人
                Cursor phoneCursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                        PHONES_PROJECTION, null, null, null);
                if (phoneCursor != null) {
                    while (phoneCursor.moveToNext()) {
                        HashMap<String, String> map = new HashMap<String, String>();

                        // 得到联系人名称
                        String contactName = phoneCursor
                                .getString(PHONES_DISPLAY_NAME_INDEX);
                        // 得到手机号码
                        String phoneNumber = phoneCursor.getString(PHONES_NUMBER_INDEX);
                        // 当手机号码为空的或者为空字段 跳过当前循环
                        if (TextUtils.isEmpty(phoneNumber))
                            continue;

                        // 得到联系人ID
                        Long contactid = phoneCursor.getLong(PHONES_CONTACT_ID_INDEX);

                        // 得到联系人头像ID
                        Long photoid = phoneCursor.getLong(PHONES_PHOTO_ID_INDEX);

                        // 得到联系人头像Bitamp

                        map.put("name", contactName);
                        phoneNumber = phoneNumber.replaceAll("-", "");
                        phoneNumber = phoneNumber.replace("+86", "");
                        phoneNumber = phoneNumber.replace("%32", "");//空格
                        map.put("phone", phoneNumber);
                        map.put("tianjia", "1");
                        boolean flag = true;
                        for (HashMap<String, String> m : contactsData) {
                            if (m.containsValue(contactName) && m.containsValue(phoneNumber)) {
                                flag = false;
                                break;
                            }
                        }
                        if (flag) {
                            contactsData.add(map);
                        }
                    }
                    phoneCursor.close();
                }
                callback.callback(contactsData);
            }

        }).start();
    }
}
